package com.hcj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hcj.pojo.Category;
import com.hcj.pojo.Product;
import com.hcj.service.CategoryService;
import com.hcj.service.ProductService;

import com.hcj.util.MyResponse;
import com.hcj.util.SnowflakeFileNameGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/product")
public class  ProductController {

    @Autowired
    private ProductService service;

    @Autowired
    private Environment env;
    @Autowired
    private CategoryService categoryService;

    private SnowflakeFileNameGenerator generator = new SnowflakeFileNameGenerator(1);

    // 添加商品
    @RequestMapping(value = "/add")
    MyResponse add(Product product, MultipartFile img) throws IOException {

        System.out.println("收到添加商品的请求！！");
        // 如果用户上传了图片
        if (img != null) {
            System.out.println("img = " + img.getOriginalFilename());
            // 获取上传文件的存储路径
            String path = env.getProperty("user.file.upload-path");


            // 使用雪花算法来计算一个新的文件名
            String newName = generator.generateFileName() + "." + img.getOriginalFilename().split("\\.")[1];

            // 将图片文件移动到存储路径
            img.transferTo(new File(path + "/" + newName));
            System.out.println("上传文件接收完成！");

            product.setImgpath(newName);
        }

        // 手动给 product 设置 createTime
        product.setCraeteTime(new Timestamp(new Date().getTime()));

        return service.add(product);
    }

    // 修改商品信息
    @RequestMapping(value = "/update")
    MyResponse update(Product product)
    {
        System.out.println("product = " + product);
        // 手动给 product 设置 createTime
        product.setCraeteTime(new Timestamp(new Date().getTime()));

        return service.update(product);
    }

    // 按照商品名、商品详情 模糊查询
    @RequestMapping(value = "/keyword")
    Page<Product> selectByNameOrDetailPaging(String keyword, Integer currentPage, Integer pageSize) {
        currentPage = currentPage == null ? 1 : currentPage;
        pageSize = pageSize == null ? 5 : pageSize;
        System.out.println("keyword = " + keyword);
        // 如果没有传递 keyword 参数，其实就是要做无条件的查询
        if (keyword.equals("")) {
            return service.selectAllPaging(currentPage, pageSize);
        }

        return service.selectByNameOrDetailPaging(keyword, currentPage, pageSize);
    }

    // 获取全部商品列表
    @RequestMapping("/all")
    Page<Product> selectAllPaging(Integer currentPage, Integer pageSize) {
        currentPage = currentPage == null ? 1 : currentPage;
        pageSize = pageSize == null ? 5 : pageSize;

        return service.selectAllPaging(currentPage, pageSize);
    }

    // 获取一个商品
    @RequestMapping(value = "/getOne", params = {"id"})
    Product selectOneById(Integer id) {
        return service.selectOneById(id);
    }

    // 按 分类 获取（不分页）默认返回四条商品信息
    @RequestMapping(value = "/getByCategory", params = {"category"})
    List<Product> selectByCategory(String category) {
        return service.selectByCategory(category);
    }

    // 按类别获取（分页）
    @RequestMapping(value = "/getAllCategory", params = {"category"})
    Page<Product> selectByCategory(String category, Integer currentPage, Integer pageSize) {
        currentPage = currentPage == null ? 1 : currentPage;
        pageSize = pageSize == null ? 5 : pageSize;

        return service.selectByCategory(category, currentPage, pageSize);
    }
    @RequestMapping("/selectByCategory")
    //返回分类别返回list数据
    HashMap<String,List<Product>> selectByCategory(){
        HashMap<String,List<Product>> map = new HashMap<>();

        //通过分类方法来获取具体类别
        List<Category> categories = categoryService.selectAll();



//        String[] category = {"绿茶" , "乌龙茶 ","白茶" , "红茶" ,"普洱茶"};
        for (int i = 0; i < categories.size(); i++) {
            List<Product> productList1 = new ArrayList<>();
            Integer addLogo = 0;
            System.out.println("categories.get(i).getName() = " + categories.get(i).getName());
            List<Product> productList = service.selectByCategory(categories.get(i).getName());
            System.out.println(productList.size());
            System.out.println("productList = " + productList);
            for (int j = 0; j < productList.size(); j++) {
                //判断商品是否处于在售状态
                if (productList.get(j).getStatus()==1){

                    productList1.add(addLogo,productList.get(j));
                    addLogo++;

                }
            }
            map.put(categories.get(i).getName(),productList1);

        }
        return map;
    }
    //按照商品销售状态查询
    @RequestMapping("/select/status")
    Page<Product> selectByStatus(Integer status,Integer currentPage,Integer pageSize){
        currentPage = currentPage == null ? 1 : currentPage;
        pageSize = pageSize == null ? 5 : pageSize;
        return service.selectByStatus(status,currentPage,pageSize);

    }
    //用过id删除
    @RequestMapping("/delete")
    MyResponse delete(Integer id){
        boolean delete = service.delete(id);
        if (delete){
            return new  MyResponse("100","删除成功");
        }else return new MyResponse("200","删除异常!");

    }
    //通过name查询
    @RequestMapping("/select/name")
    Product selectByName(String name){
        return service.selectByName(name);
    }

    @RequestMapping("/select/likeName")
    List<Product> selectLikeName(String name){
        System.out.println("name = " + name);

        return service.selectByLikeName(name);
    }


}
